#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2020/4/7 11:39
# @Author  : yangdy
# @Email   : yangdy@egu360.com
# @File    : 面试题 01.07. 旋转矩阵.2020-04-07.py
# @Software: PyCharm

__author__ = 'yangdy'

from typing import List


class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        if n <= 0:
            return
        h = (n - 1) / 2
        # ih = round(h)  # python3中round为四舍六入五成双不是四射五入
        # 两种方案:
        # ih = int(h) + ((n -1) & 1)  # 注意&的优先级比+低。。
        ih = int(h) + (n - 1) % 2
        # print(h, ih)
        for x1 in range(ih):
            for y1 in range(ih):
                x2, y2 = y1, int(h * 2) - x1
                x3, y3 = int(h * 2) - x1, int(h * 2) - y1
                x4, y4 = int(h * 2) - y1, x1

                matrix[x1][y1], matrix[x2][y2], matrix[x3][y3], matrix[x4][y4] = \
                    matrix[x4][y4], matrix[x1][y1], matrix[x2][y2], matrix[x3][y3]
        if n % 2 == 1:
            y1 = ih
            for x1 in range(ih):
                x2, y2 = y1, ih * 2 - x1
                x3, y3 = ih * 2 - x1, ih * 2 - y1
                x4, y4 = ih * 2 - y1, x1

                matrix[x1][y1], matrix[x2][y2], matrix[x3][y3], matrix[x4][y4] = \
                    matrix[x4][y4], matrix[x1][y1], matrix[x2][y2], matrix[x3][y3]
        return


solve = Solution()
mm = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
print('q:', mm)
solve.rotate(mm)
print('ans:', mm)

mm2 = [
  [5, 1, 9, 11],
  [2, 4, 8, 10],
  [13, 3, 6, 7],
  [15, 14, 12, 16]
]
print('q:', mm2)
solve.rotate(mm2)
print(mm2)

mm3 = [
    [1, 2],
    [3, 4]
]
print('q:', mm3)
solve.rotate(mm3)
print(mm3)
